<template>
  <!-- 房源库 -->
  <div class="housingArchivePage">
    <!-- tag菜单组件 -->
    <IncomeTagMenu projectName="资产经营管理" menuName="资源库" />
    <div class="content">
      <div class="searchBox">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.searchVal"
              class="searchInputBox"
              placeholder="根据资产名称搜索"
              maxlength="32"
              clearable
              @keyup.enter="doSearch"
            />
          </el-form-item>
          <el-form-item label="房源所属业态">
            <el-select
              v-model="searchForm.businessType"
              class="businessTypeSelectBox"
              placeholder="请选择所属业态"
            >
              <el-option
                v-for="item in searchForm.busnTypeOptionsArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="房源用途">
            <el-select v-model="searchForm.useType" class="w-135">
              <el-option
                v-for="item in searchForm.useTypeOptionsArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="房源状态">
            <el-select v-model="searchForm.status" class="w-135">
              <el-option
                v-for="item in searchForm.statusOptionsArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-button
            color="#FF7B50"
            style="color: #fff"
            type="primary"
            class="m-r10"
            @click="doSearch"
            >查看</el-button
          >
          <el-button style="" color="#F0F0F0" @click="doReset">重置</el-button>
          <el-divider direction="vertical" class="dividerStyle" />
          <el-button plain color="#FF7B50" class="houseInputBtn" @click="addHouse">
            <img src="@/assets/iconImg/daoru.png" alt="" />
            房源录入</el-button
          >
        </el-form>
      </div>
      <PublicStatistics :cardArr="cardInfo.cardArr" getWidth="540px"></PublicStatistics>
      <el-table
        ref="multipleTable"
        v-loading="tableLoadingFlag"
        :data="state.tableData"
        tooltip-effect="dark"
        style="width: 100%; margin-bottom: 23px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="40" />
        <el-table-column prop="index" label="序号" width="55" align="center" />
        <el-table-column prop="assetsName" label="关联资产名" align="center">
        </el-table-column>
        <el-table-column prop="assetsType" label="资产类型" width="100" align="center">
          <template #default="scope">
            {{ getAssetsTypeVal(scope.row.assetsType) }}
          </template>
        </el-table-column>
        <el-table-column prop="housingNumber" label="门牌号码" align="center">
        </el-table-column>
        <el-table-column prop="businessType" label="所属业态" width="80" align="center">
          <template #default="scope">
            {{ getBusTypeVal(scope.row.businessType) }}
          </template>
        </el-table-column>
        <el-table-column prop="useType" label="房源用途" width="80" align="center">
          <template #default="scope">
            {{ getUseTypeVal(scope.row.useType) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="房源状态" width="80" align="center">
          <template #default="scope">
            {{
              scope.row.status == 1
                ? "在用"
                : scope.row.status == 0
                ? "闲置"
                : scope.row.status == -1
                ? "停用"
                : scope.row.status == 2
                ? "已出租"
                : "--"
            }}
          </template>
        </el-table-column>
        <el-table-column prop="area" label="房源持有面积(㎡)" width="140" align="center">
        </el-table-column>
        <el-table-column prop="createTime" label="建档时间" width="170" align="center">
          <template #default="scope">
            {{
              scope.row.createTime
                ? dayjs(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss")
                : "--"
            }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template #default="scope">
            <el-button color="#FF7B50" style="color: #fff" @click="goDetail(scope.row)"
              >详情</el-button
            >

            <el-button
              :color="scope.row.status==-1 ? '#068e1d' : '#bc0b0c'"
              style="color: #fff"
              @click="changeState(scope.row)"
              >{{ scope.row.status != -1 ? "停用" : "启用" }}</el-button
            >

            <el-button plain class="button_edit" @click="goEdit(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-button
        class="f-l"
        color="#F12527"
        style="color: #fff; width: 76px; height: 40px"
        :disabled="state.deletBtnDisFlag"
        @click="doDelet"
        >删除</el-button
      >
      <el-pagination
        v-model:page-size="defualtPageSize"
        :total="state.total"
        :page-sizes="[20, 30, 40, 50, 100, 150, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="state.currentPage"
        @current-change="pageChang"
      />
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from "vue";
import { useRouter } from "vue-router";
import {
  ElForm,
  ElFormItem,
  ElTable,
  ElTableColumn,
  ElSelect,
  ElOption,
  ElPagination,
  ElDivider,
  ElMessage,
  ElMessageBox,
} from "element-plus";
import dayjs from "dayjs";
import {
  houseUsingTypeOptionArr,
  houseBusinessTypeOptions,
  houseStateOptionsArr,
  assetsTypeOptionsArr,
} from "@/common/dict/dictCollect";
import PublicStatistics from "@/components/PublicStatistics.vue";
import { jsonParseStringfy, numToFixed } from "@/common/utils/GlobalUtils";
import IncomeTagMenu from "@/components/IncomeTagMenu.vue";
import { housingApi } from "@/api/assets";
const router = useRouter();

const changeState = (row) => {
  const dMsg = row.status != -1 ? "停用" : "启用";
  // 确认弹窗
  ElMessageBox.confirm(
    "<img style='width:20px;height:20px;margin-right: 5px;margin-top: 2px;' src=" +
      iconUrl +
      " />是否确认" +
      dMsg +
      "所选房源数据？",
    "房源" + dMsg + "确认",
    {
      customClass: "deletConfirmBox",
      confirmButtonText: dMsg,
      cancelButtonText: "取消",
      dangerouslyUseHTMLString: true,
      center: true,
      closeOnClickModal: false,
    }
  )
    .then(() => {
      console.log(111);

      const status = row.status != -1 ? -1 : 0;
      console.log(row);
      housingApi.updateHousing({ ...row, status }).then((res) => {
        const { code, data, msg } = res;
        console.log(res);
        if (code === "200") {
          ElMessage({
            type: "success",
            message: msg,
          });
          doSearch();
        }
      });
    })
    .catch(() => {});
};

const searchForm = reactive({
  searchVal: null,
  businessType: "",
  busnTypeOptionsArr: [],
  useType: "",
  useTypeOptionsArr: [],
  status: "",
  statusOptionsArr: [],
});

// 初始化时，给查询条件添加'全部'选项
const initQueryCondition = () => {
  // 所属业态选项
  let newHouseBusinessTypeOptions = jsonParseStringfy(houseBusinessTypeOptions);
  newHouseBusinessTypeOptions.unshift({ label: "全部", value: "" });
  searchForm.busnTypeOptionsArr = newHouseBusinessTypeOptions;
  // 房源用途选项
  let newHouseUsingTypeOptions = jsonParseStringfy(houseUsingTypeOptionArr);
  newHouseUsingTypeOptions.unshift({ label: "全部", value: "" });
  searchForm.useTypeOptionsArr = newHouseUsingTypeOptions;
  // 房源状态选项
  let newHouseStateOptions = jsonParseStringfy(houseStateOptionsArr);
  newHouseStateOptions.unshift({ label: "全部", value: "" });
  searchForm.statusOptionsArr = newHouseStateOptions;
};

const getBusTypeVal = (key) => {
  let getVal = "--";
  houseBusinessTypeOptions.map((n, i) => {
    if (key == n.value) {
      getVal = n.label;
    }
  });
  return getVal;
};
const getAssetsTypeVal = (key) => {
  let getVal = "--";
  assetsTypeOptionsArr.map((n, i) => {
    if (key == n.value) {
      getVal = n.label;
    }
  });
  return getVal;
};
const getUseTypeVal = (key) => {
  let getVal = "--";
  houseUsingTypeOptionArr.map((n, i) => {
    if (key == n.value) {
      getVal = n.label;
    }
  });
  return getVal;
};

const doSearch = () => {
  initAmountData();
  initTableData();
};

const doReset = () => {
  searchForm.searchVal = null;
  searchForm.businessType = "";
  searchForm.useType = "";
  searchForm.status = "";
  initTableData();
};

const cardInfo = reactive({
  cardArr: [
    {
      title: "房源总数",
      num: "--",
      url: require("@/assets/iconImg/fangyuanzs.png"),
      unit: "个",
    },
    {
      title: "房源总持有面积",
      num: "--",
      url: require("@/assets/iconImg/keyongmj.png"),
      unit: "㎡",
    },
  ],
});
// 初始获取资产总数
const initAmountData = () => {
  housingApi.getHousingStatistics().then((res) => {
    const { code, data } = res;
    if (code == 200) {
      cardInfo.cardArr[0].num = numToFixed(data.totalNum).split("&")[0];
      cardInfo.cardArr[0].unit = numToFixed(data.totalNum).split("&")[1]
        ? numToFixed(data.totalNum).split("&")[1] + "个"
        : cardInfo.cardArr[0].unit;

      cardInfo.cardArr[1].num = numToFixed(data.totalArea, 2).split("&")[0];
      cardInfo.cardArr[1].unit = numToFixed(data.totalArea, 2).split("&")[1]
        ? numToFixed(data.totalArea, 2).split("&")[1] + "㎡"
        : cardInfo.cardArr[1].unit;
    }
  });
};

// table相关
const defualtPageSize = ref(50);
const tableLoadingFlag = ref(false);
const state = reactive({
  deletBtnDisFlag: true,
  tableData: [],
  total: 1, // 总条数
  currentPage: 1, // 当前页
});

// 初始获取table数据
const initTableData = () => {
  tableLoadingFlag.value = true;
  const params = {
    pageNum: state.currentPage,
    pageSize: defualtPageSize.value,
    param: {
      queryName: searchForm.searchVal,
      businessType: searchForm.businessType,
      useType: searchForm.useType,
      status: searchForm.status,
    },
  };
  housingApi.getHousingPage(params).then((res) => {
    const { code, data, msg } = res;
    if (code == 200) {
      state.tableData = data.content.map((n, i) => {
        n.index = i + 1;
        return n;
      });
      state.total = data.totalSize;
      tableLoadingFlag.value = false;
    } else {
      tableLoadingFlag.value = false;
    }
  });
};

const pageChang = (val) => {
  state.currentPage = val;
  initTableData();
};

// table的复选
let selectedColumnsArr = ref([]);
// watch( //使用ref定义未初始化的数组，监听时不能用.value且必须是深度监听。这种写法不仅可以监听数组本身的变化，也可以监听数组元素的变化。
//   selectedColumnsArr,
//   (newValue) => {
//     console.log('选择数组变化了', jsonParseStringfy(newValue))
//     selectedColumnsArr.value = jsonParseStringfy(newValue)
//   },
//   {deep: true}
// )
const handleSelectionChange = (val) => {
  selectedColumnsArr.value = jsonParseStringfy(val);
  selectedColumnsArr.value.length
    ? (state.deletBtnDisFlag = false)
    : (state.deletBtnDisFlag = true);
};

// 批量删除房源
const iconUrl = require("@/assets/iconImg/warning.png");
const doDelet = () => {
  let deletIdArr = [];
  if (selectedColumnsArr.value.length) {
    selectedColumnsArr.value.map((n) => {
      deletIdArr.push(n.housingId);
    });
  }
  // 确认弹窗
  ElMessageBox.confirm(
    "<img style='width:20px;height:20px;margin-right: 5px;margin-top: 2px;' src=" +
      iconUrl +
      " />是否确认删除所选档案，数据删除后不可恢复!",
    "档案删除确认",
    {
      customClass: "deletConfirmBox",
      confirmButtonText: "删除",
      cancelButtonText: "取消",
      dangerouslyUseHTMLString: true,
      center: true,
      closeOnClickModal: false,
    }
  )
    .then(() => {
      housingApi.housingDelete({ housingIds: deletIdArr }).then((res) => {
        const { code, data, msg } = res;
        if (code == 200) {
          ElMessage({
            type: "success",
            message: "房源删除成功",
          });
          initAmountData();
          initTableData();
        }
      });
    })
    .catch(() => {});
};

// 录入
const addHouse = () => {
  router.push({
    path: "/asset/company/housingInformationAdd/pageType=add",
  });
};
// 详情
const goDetail = (row) => {
  router.push({
    path: "/asset/company/housingInformationDetails/" + row.housingId,
  });
};
// 编辑
const goEdit = (row) => {
  router.push({
    path: `/asset/company/housingInformationEdit/pageType=edit&id=${row.housingId}`,
  });
};

onMounted(() => {
  initAmountData();
  initTableData();
  initQueryCondition();
});
</script>

<style lang="scss" scoped>
.housingArchivePage {
  .content {
    .w-135 {
      width: 135px;
    }
    .searchBox {
      margin-bottom: 38px;
      .demo-form-inline {
        .el-form-item {
          margin-bottom: 0;
          .el-form-item__content {
            .searchInputBox {
              width: 150px;
            }
            .businessTypeSelectBox {
              width: 120px;
            }
          }
        }
        .dividerStyle {
          height: 40px;
          margin: 0 30px;
        }
        .houseInputBtn {
          img {
            width: 18px;
            height: 18px;
          }
          &:hover {
            background-color: #fff;
            color: $btn-defualt-tx-color;
          }
        }
      }
    }
  }
}
</style>
<style lang="scss" scoped>
.housingArchivePage {
  :deep(.el-table) {
    .el-table__body {
      .cell {
        .el-button {
          width: 68px;
          height: 31px;
        }
      }
    }
  }
}
</style>
